package internal

import (
	"fmt"
	"log"

	"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
	"github.com/pkg/errors"
)

func Upload(endPoint, ak, sk, bucket, key, sourceFile string) error {
	obsClient, err := obs.New(ak, sk, endPoint)
	if err != nil {
		return errors.Wrapf(err, "Create obsClient error")

	}
	input := &obs.PutFileInput{}
	// 指定存储桶名称
	input.Bucket = bucket
	// 指定上传对象
	input.Key = key
	// 指定本地文件
	input.SourceFile = sourceFile
	// 文件上传
	output, err := obsClient.PutFile(input)
	if err == nil {
		log.Printf("Put file(%s) under the bucket(%s) successful!\n", input.Key, input.Bucket)
		log.Printf("StorageClass:%s, ETag:%s\n", output.StorageClass, output.ETag)
		return nil
	}
	fmt.Printf("Put file(%s) under the bucket(%s) fail!\n", input.Key, input.Bucket)
	var obsError obs.ObsError
	if errors.As(err, &obsError) {
		return errors.Wrapf(obsError, "An ObsError was found, which means your request sent to OBS was rejected with an error response.")
	} else {
		return errors.Wrapf(err, "An Exception was found, which means the client encountered an internal problem when attempting to communicate with OBS, for example, the client was unable to access the network.")
	}
}
